package com.ssdp.utils;

import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
 * @author syo 2319615164@qq.com
 * @description 向FTP服务器上传文件
 * @date 2024/3/14
 * @Copyright syo
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class UploadUtils {

    @Value("${ssdp.upload.host}")
    private static String host;

    @Value("${ssdp.upload.port}")
    private static int port;

    @Value("${ssdp.upload.username}")
    private static String username;

    @Value("${ssdp.upload.password}")
    private static String password;

    private static final Logger logger = LoggerFactory.getLogger(UploadUtils.class);

    private static ChannelSftp sftp = null;

    /**
     * 向FTP服务器上传文件
     * @param filename          上传到FTP服务器上的文件名
     * @param input             输入流
     * @return                  成功返回true，否则返回false
     */
    public static boolean uploadFile(String filename, InputStream input) {
        boolean result = false;
        FTPClient ftp = new FTPClient();
        File file = null;
        try {
            JSch jsch = new JSch();
            // 获取sshSession  账号-ip-端口
            Session sshSession = jsch.getSession(username, host, port);

            // 添加密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();

            // 严格主机密钥检查
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);

            // 开启sshSession链接
            sshSession.connect();
            // 获取sftp通道
            Channel channel = sshSession.openChannel("sftp");

            // 开启
            channel.connect();
            sftp = (ChannelSftp) channel;

            // 服务器路径
            // file = new File("/www/server/nginx/html/hmdp/imgs");
            // 设置为被动模式
            ftp.enterLocalPassiveMode();
            // 设置上传文件的类型为二进制类型
            // 进入到要上传的目录  然后上传文件
            int i = filename.lastIndexOf('/');

            // 目录
            String prefix = filename.substring(0, i + 1);

            // 文件名后缀
            String suffix = filename.substring(i + 1);

            // 整体目录名
            String allPath = "/www/server/nginx/html/hmdp/imgs" + prefix;

            try {
                sftp.cd(allPath);
            } catch (SftpException e) {
                // 目录不存在，则创建文件夹
                String[] dirs = allPath.split("/");
                String tempPath = "";
                int index = 0;
                mkdirDir(dirs, tempPath, dirs.length, index);
            }

            sftp.cd(allPath);
            sftp.put(input, suffix);
            input.close();
            result = true;
        } catch (Exception e) {
            logger.error("上传文件错误！", e);
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error("关闭远程连接错误！", ioe);
                }
            }
        }
        return result;
    }


    public static void mkdirDir(String[] dirs, String tempPath, int length, int index) {
        // 以"/a/b/c/d"为例按"/"分隔后,第0位是"";故下标从1开始
        index++;
        if (index < length) {
            // 目录不存在，则创建文件夹
            tempPath += "/" + dirs[index];
        }
        try {
            sftp.cd(tempPath);
            if (index < length) {
                mkdirDir(dirs, tempPath, length, index);
            }
        } catch (SftpException ex) {
            try {
                sftp.mkdir(tempPath);
                sftp.cd(tempPath);
            } catch (SftpException e) {
                logger.error("文件目录创建失败！", e);
            }
            mkdirDir(dirs, tempPath, length, index);
        }
    }
}




